#!/usr/bin/env python

#
# SMPP Bulk Tx Submit_SM
# by: Yusuf Kaka, MTN, 2006
#
import sys,smpplib,time,MySQLdb,threading
from collections import deque

class Loader(threading.Thread):
    def __init__(self):
        self.msgQ = deque()
        self.dbHost = "localhost"
        self.dbUser = "smsuser"
        self.dbPass = "smspass"
        self.dbName = "smsDb"
        self.alive = True
        threading.Thread.__init__ ( self )
    
              
    def run(self):
        while self.alive:
            if len(self.msgQ) > 0:
                print("Queue size: "+str(len(self.msgQ)))
                message = self.msgQ.pop()
                srcNum = message[0]
                msg = message[2]
                desNum = message[1]
                self.store_msg(srcNum,desNum, msg)
            else:
                time.sleep(10)
        
    def getQ(self):
        return self.msgQ
    
    def store_msg(self,src,des,msg):
        # connect
        msg = msg.replace("\""," ")
        msg = msg.replace("\'"," ")
        msg = msg.replace("`"," ")
        #msg = unicode(msg,'latin-1') 
        campaignTxt = msg.split(' ')[0].lower()[:20]
        
        db = MySQLdb.connect(host=self.dbHost, user=self.dbUser, passwd=self.dbPass,
        db=self.dbName)
        
        # create a cursor
        cursor = db.cursor()
        
        # execute SQL statement
        cursor.execute("SELECT * FROM `campaigns` WHERE `campaign` = \""+campaignTxt+"\"")
        
        # get the resultset as a tuple
        result = cursor.fetchall()
        
        # iterate through resultset
        if len(result) == 0:
            campaignTxt = "default"
        print "Inserting into DB"
        cursor.execute(" INSERT INTO `messages` ( `src` , `des` , `message`, `campaign`) VALUES ('"+src+"', '"+des+"', '"+msg+"', '"+campaignTxt+"')")
        #cursor.execute("CREATE TABLE `"+number+"` (`ID` int(11) NOT NULL auto_increment,`Timestamp` timestamp NOT NULL default CURRENT_TIMESTAMP, `Msg` text NOT NULL, PRIMARY KEY  (`ID`)) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2;")
           
           
    def shutDown(self):
        self.alive = False
   
if __name__ == '__main__':
    print "hello"
